package priv.wangy.micro.common.po.valid.validator;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import lombok.Getter;
import org.springframework.util.StringUtils;
import priv.wangy.micro.common.po.valid.ZhAndEn;

import java.util.regex.Pattern;

/**
 * @author 张嘉琪
 * @since 2023-04-09
 */
public class ZhAndEnValidator implements ConstraintValidator<ZhAndEn, String> {

    private ZhAndEnPattern mode;
    private int min;
    private int max;

    @Override
    public void initialize(ZhAndEn constraintAnnotation) {
        this.mode = constraintAnnotation.mode();
        this.min = constraintAnnotation.min();
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.hasLength(value)) {
            if (value.length() < min || value.length() > max) {
                return false;
            }
        } else {
            return min <= 0;
        }
        return mode.getPattern().matcher(value).matches();
    }

    @Getter
    public enum ZhAndEnPattern {
        /**
         * 中文、英文、数字及中英文标点
         */
        FULL(Pattern.compile("^[\\u4e00-\\u9fa5_a-zA-Z0-9\\s·~！@#￥%…&*（）—\\-+=【】{}、|；‘’：“”《》？，。`!$^()\\[\\]\\\\;':\",./<>?]+$")),
        /**
         * 中文
         */
        ZH_ONLY(Pattern.compile("^[\\u4e00-\\u9fa5]+$")),
        /**
         * 英文
         */
        EN_ONLY(Pattern.compile("^[a-zA-Z]+$")),
        /**
         * 数字
         */
        DIGIT(Pattern.compile("^[0-9]+$")),
        /**
         * 中文+英文
         */
        ZH_EN(Pattern.compile("^[\\u4e00-\\u9fa5a-zA-Z0-9]+$")),
        /**
         * 中文+数字
         */
        ZH_DIGIT(Pattern.compile("^[\\u4e00-\\u9fa50-9]+$")),
        /**
         * 中文+‘·’
         */
        ZH_DOT(Pattern.compile("^[\\u4e00-\\u9fa5·]+$")),
        /**
         * 英文+数字
         */
        EN_DIGIT(Pattern.compile("^[a-zA-Z0-9]+$")),
        /**
         * 英文（大写）+数字
         */
        EN_UP_DIGIT(Pattern.compile("^[A-Z0-9]+$")),
        /**
         * 中文+英文+‘·’+数字
         */
        NAME_OR_NO(Pattern.compile("^[\\u4e00-\\u9fa5·A-Z0-9]+$"));

        private final Pattern pattern;

        ZhAndEnPattern(Pattern pattern) {
            this.pattern = pattern;
        }

    }
}
